const {Schema, model} = require('mongoose')
const bcrypt = require('bcrypt')

const userSchema = new Schema({
  id: {
    type: String,
    required: true,
    unique: true,
  },
  email: {
    type: String,
    required: true,
    unique: true,
  },
  name: {
    type: String,
    required: false,
  },
  password: {
    type: String,
    required: true,
  },
  confirm: {
    type: Boolean,
    required: false,
  },
  lastname: {
    type: String,
    required: false,
  },
  occupation: {
    type: String,
    required: false,
  },
})

userSchema.pre('save', async function (next) {
  this.password = await bcrypt.hash(this.password, 10)
  next()
})

userSchema.methods.isValidPassword = async function (password) {
  const user = this
  return await bcrypt.compare(password, user.password)
}

module.exports = model('Users', userSchema)
